package com.itheima.system.controller;

import com.itheima.common.controller.BaseController;
import com.itheima.common.entity.Result;
import com.itheima.common.entity.ResultCode;
import com.itheima.common.utils.IdWorker;
import com.itheima.common.utils.ImportExcelUtils;
import com.itheima.common.utils.POIUtils;
import com.itheima.system.client.DepartmentFeignClient;
import com.itheima.system.pojo.User;
import com.itheima.system.pojo.client.Department;
import com.itheima.system.pojo.vo.AssignRoleVo;
import com.itheima.system.service.RoleService;
import com.itheima.system.service.UserService;
import com.itheima.common.utils.BeanMapUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author IntelliJ IDEA
 * @date 2020/10/23  10:31
 * @CrossOrigin //解决跨域
 */
@CrossOrigin
@RestController
@RequestMapping("/sys")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    @Autowired
    private DepartmentFeignClient departmentFeignClient;

    private static final String DEFAULTSERVICESTATUS="1";

    private static final String DEFAULTSTATUS="1";

    private static final String DEFAULTPASSWORD="123456";

    private static final String USER="user";

    @Autowired
    private IdWorker idWorker;



    /**
     * fegin客户端测试2
     */
  //  @GetMapping("/test")
//    public Result test(){
//       return new Result(ResultCode.SUCCESS,departmentFeignClient.findDepartmentByCodeAndCompanyId("DEPT-DEV","1"));
//    }

    /**
     * 新增用户
     */
    @PostMapping("/user")
    public Result addUser(@RequestBody User user){
        user.setCompanyId(this.companyId);
        user.setCompanyName(this.companyName);
        user.setEnableState("1");
        Integer rows=userService.addUser(user);
        if(rows<1){
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping("/user")
    public Result findAllUserByPage(Integer page,Integer size,@RequestParam(required = false) Map<String,Object> map){
        map.put("companyId",this.companyId);
        return new Result(ResultCode.SUCCESS,userService.findAllUserByPage(page,size,map));
    }

    /**
     * 根据id查询用户
     */
    @GetMapping("/user/{id}")
    public Result findUserById(@PathVariable("id") String id){
        //查询用户
        User user = userService.findUserById(id);
        Map<String,Object> map=BeanMapUtils.beanToMap(user);
        //根据用户id查询角色结合
        Set<String> roleIds=roleService.findRoleIdsByUserId(user.getId());
        map.put("roleIds",roleIds);
        return new Result(ResultCode.SUCCESS,map);
    }

    /**
     * 根据id删除用户
     */
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE,name = "API-USER-DELETE")
    public Result deleteUserById(@PathVariable("id") String id){
        Integer rows=userService.deleteUserById(id);
        if(rows<1){
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 修改用户
     */
    @PutMapping("/user/{id}")
    public Result updateUserByUserId(@PathVariable("id") String id,@RequestBody User user){
        user.setId(id);
        Integer rows=userService.updateUserByUserId(user);
        if(rows<1){
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 给用户分配角色
     */
    @PutMapping("/user/assignRoles")
    public Result assignRoles(@RequestBody AssignRoleVo assignRoleVo){
        try{
            userService.assignRoles(assignRoleVo);
            return new Result(ResultCode.SUCCESS);
        }catch (Exception e){
            return new Result(ResultCode.FAIL);
        }
    }

    /**
     * 用户登录，登录成功后返回token信息
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        try {
            String token= userService.login(user);
            return new Result(ResultCode.SUCCESS,token);
        }catch (Exception e){
            return new Result(ResultCode.USERNOTFOUNDORPASSWORDERROR);
        }
    }

    /**
     * 身份验证（token验证），获取个人信息
     */
    @PostMapping("/profile")
    public Result profile(HttpServletRequest request){
        try{
            return userService.profile(request,this.claims);
        }catch (Exception e){
            return new Result(500,e.getMessage(),false);
        }
    }
//    @PostMapping("/profile")
//    public Result profile(HttpServletRequest request){
//        try{
//            return userService.profile(request);
//        }catch (Exception e){
//            return new Result(500,e.getMessage(),false);
//        }
//    }


    /**
     * user/simple
     */
    @RequestMapping("/user/simple")
    public Result simple(){
        return new Result(ResultCode.SUCCESS,userService.simple(this.companyId));
    }

    /**
     * 员工导入
     */
//    @PostMapping("/user/import")
//    public Result ExceImport(@RequestParam("file") MultipartFile file){
//        List<User> userList=new ArrayList<User>();
//        try{
//            if(file!=null){
//                //根据Excel创建工作簿
//                Workbook wb=new XSSFWorkbook(file.getInputStream());
//                //获取第一个sheet
//                Sheet sheet = wb.getSheetAt(0);
//                /**
//                 * POI解析  sheet.getLastRowNum() 获取的索引数
//                 *          row.getLastCellNum() 获取的是单元格数
//                 */
//                for(Integer rowNum=1;rowNum<=sheet.getLastRowNum();rowNum++){
//                    Row row = sheet.getRow(rowNum);
//                    Object[] values=new Object[row.getLastCellNum()];
//                    for(Integer cellNum=1;cellNum<row.getLastCellNum();cellNum++){
//                        Cell cell = row.getCell(cellNum);
//                        Object value = POIUtils.getCellValue(cell);
//                        values[cellNum]= value;
//                    }
//                    User user=new User(values);
//                    //其他属性的设置
//                    //初始密码
//                    user.setPassword(DEFAULTPASSWORD);
//                    //id
//                    user.setId(String.valueOf(idWorker.nextId()));
//                    //基本属性
//                    user.setCompanyId(companyId);
//                    user.setCompanyName(companyName);
//                    user.setInServiceStatus(DEFAULTSERVICESTATUS);
//                    user.setEnableState(DEFAULTSTATUS);
//                    user.setCreateTime(new Date());
//                    user.setLevel(USER);
//                    //departmentId和departName设置
//                    Department department = departmentFeignClient.findByCode(user.getDepartmentCode(), this.companyId);
//                    if(department!=null){
//                        user.setDepartmentId(department.getId());
//                        user.setDepartmentName(department.getName());
//                    }else {
//                        user.setDepartmentId("");
//                        user.setDepartmentName("");
//                    }
//                    userList.add(user);
//                }
//                userService.savaAll(userList,companyId,companyName);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            return new Result(ResultCode.FAIL);
//        }
//        return new Result(ResultCode.SUCCESS);
//    }


    /**
     * 基于注解开发方式 员工导入
     */
    @PostMapping("/user/import")
    public Result ExceImport(@RequestParam("file") MultipartFile file){
        try {
            ImportExcelUtils<User> importExcelUtils=new ImportExcelUtils<User>(User.class);
            List<User> userList = importExcelUtils.readExcel(file.getInputStream(), 1, 1);
            for (User user : userList) {
                //其他属性的设置
                //初始密码
                user.setPassword(DEFAULTPASSWORD);
                //id
                user.setId(String.valueOf(idWorker.nextId()));
                //基本属性
                user.setCompanyId(companyId);
                user.setCompanyName(companyName);
                user.setInServiceStatus(DEFAULTSERVICESTATUS);
                user.setEnableState(DEFAULTSTATUS);
                user.setCreateTime(new Date());
                user.setLevel(USER);
                //departmentId和departName设置
                Department department = departmentFeignClient.findByCode(user.getDepartmentCode(),this.companyId);
                if(department!=null){
                    user.setDepartmentId(department.getId());
                    user.setDepartmentName(department.getName());
                }else {
                    user.setDepartmentId("");
                    user.setDepartmentName("");
                }
            }
            //批量保存数据
            //userService.savaAll(userList,"1","传智播客");
            userService.savaAll(userList,this.companyId,this.companyName);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }
    }


    /**
     * 头像上传
     */
    @PostMapping("/user/upload/{userId}")
    public Result uploadImg(@PathVariable("userId") String userId,@RequestParam("file") MultipartFile file){
        try{
            //调用service执行头像上传
            return new Result(ResultCode.SUCCESS,userService.uploadImg(userId, file));
        }catch (Exception e){
            return new Result(ResultCode.FAIL);
        }
    }
}
